package com.authine.cloudpivot.ext.service.impl;


import cn.hutool.core.map.MapBuilder;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.engine.api.facade.SystemManagementFacade;
import com.authine.cloudpivot.engine.api.model.im.WorkRecordModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkItemModel;
import com.authine.cloudpivot.engine.api.model.system.RelatedCorpSettingModel;
import com.authine.cloudpivot.engine.domain.organization.User;
import com.authine.cloudpivot.engine.enums.type.OrgSyncType;
import com.authine.cloudpivot.engine.service.organization.UserService;
import com.authine.cloudpivot.ext.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OaWorkItemServiceImpl {
    @Value("${other.portal.sendTodo:http://120.27.239.190/api/bff/v1.2/enduser/plugin_msg_centers/create}")
    private String sendTodoUrl;
    @Value("${other.portal.deleteTodo:http://120.27.239.190/api/bff/v1.2/enduser/plugin_msg_centers/delkingdee}")
    private String deleteTodoUrl;
    @Value("${other.portal.itemPcUrl:{}/websso/index.html#/form/detail?workitemId={}&workflowInstanceId={}}")
    private String itemPcUrl;
    private static String host;


    @Value("${other.portal.sendTodo:http://120.27.239.190/api/bff/v1.2/enduser/plugin_msg_centers/create}")
    private static String sendTodoUrl1;

    private static final String subject = "请审批{}";


    @Autowired
    private UserService userService;

    @Autowired
    SystemManagementFacade systemManagementFacade;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    TokenService tokenService;


    /**
     *  发送待办
     * @param item
     * @return 0:成功,1:不需要发送,2:重试
     */
    public String sendTodo(WorkItemModel item){
        log.info("\n=============浩通门户待办>>>workDTO={}", JSON.toJSONString(item));


        User user = userService.get(item.getParticipant());
        if (user == null){
            log.info("\n==============浩通门户待办失败,待办参与者获取失败,参与者用户不存在,Participant:={}",item.getParticipant());
            return "2";
        }
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dDate=simpleDateFormat.format(new Date());

        MapBuilder<String, Object> rstBuild = MapBuilder.create(new HashMap<String, Object>())
                .put("content",item.getActivityName())
                .put("url",getUrl(item.getId(),item.getInstanceId(),itemPcUrl))
                .put("username",user.getEmployeeNo())
                .put("classify","云枢")
                .put("publishTime",dDate)
                .put("fassignId",item.getId())
                .put("originaTor","")
                .put("processTakes","");
        String appCode = item.getAppCode();
        log.info("oa待办推送,appCode={}",appCode);


        log.info("\n==============浩通门户待办 参数: oaSendToDo={}", JSONObject.toJSONString(rstBuild.build()));

        boolean b = post(sendTodoUrl, rstBuild.build());
        return b?"0":"2";
    }

    /**
     *  待办完成
     * @param workItemId
     * @return
     */
    public boolean setTodoDone(String workItemId){
        log.info("\n=============发送oa已办>>>workItemId={}", JSON.toJSONString(workItemId));
        String param = String.format("msgid=%s", workItemId);
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dDate=simpleDateFormat.format(new Date());
        MapBuilder<String, Object> rstBuild = MapBuilder.create(new HashMap<String, Object>())
                .put("content","完成待办")
                .put("url","")
                .put("username","00001")
                .put("classify","云枢")
                .put("publishTime",dDate)
                .put("fassignId",workItemId)
                .put("originaTor","")
                .put("processTakes","");
        log.info("==============delete浩通门户待办 参数: deleteToDo={}", JSONObject.toJSONString(rstBuild.build()));
        return deleted(deleteTodoUrl, rstBuild.build() );

    }


    /**
     *  删除待办
     *
     * @return
     */
    public boolean deleteToDo(WorkRecordModel workRecord){
        log.info("\n=============浩通门户待办删除>>>workRecord={}", JSON.toJSONString(workRecord));
        User user = userService.get(workRecord.getReceivers());
        if (user == null){
            log.info("\n==============浩通门户待办失败,待办参与者获取失败");
            return false;
        }
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dDate=simpleDateFormat.format(new Date());
//        String param = String.format("msgid=%s", workItemId);
        MapBuilder<String, Object> rstBuild = MapBuilder.create(new HashMap<String, Object>())
                .put("content",workRecord.getContent())
                .put("url","")
                .put("username",user.getEmployeeNo())
                .put("classify","云枢")
                .put("publishTime",dDate)
                .put("fassignId",workRecord.getWorkitemId())
                .put("originaTor","")
                .put("processTakes","");
        log.info("==============delete浩通门户待办 参数: deleteToDo={}", JSONObject.toJSONString(rstBuild.build()));
        return deleted(deleteTodoUrl, rstBuild.build() );

    }
    private boolean deleted(String url, Object param){
        HttpHeaders headers = new HttpHeaders();

        headers.set("Authorization", tokenService.getAuthorization() );

        HttpEntity entity = new HttpEntity( param, headers);

        ResponseEntity<Map> exchange = restTemplate.exchange(url, HttpMethod.DELETE, entity, Map.class);
        Map result = exchange.getBody();
        
        log.info("\n==============浩通门户待办操作 响应: rest={}",JSONObject.toJSONString(result));

        boolean success = MapUtils.getBoolean(result, "success",false);

        return success;
    }

    private boolean post(String url, Object param){
        log.info("---------OaWorkItemServiceImpl.post--------------param:{}",JSONObject.toJSONString(param));
        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.parseMediaType("application/json;charset=UTF-8"));
//        headers.add("Accept", MediaType.APPLICATION_JSON_VALUE);
        headers.set("Authorization", tokenService.getAuthorization() );

        HttpEntity stringHttpEntity = new HttpEntity( param, headers);
        log.info("---------OaWorkItemServiceImpl.post--------------url:{}",url);
        log.info("---------OaWorkItemServiceImpl.post--------------stringHttpEntity:{}",JSONObject.toJSONString(stringHttpEntity));
        Map result = restTemplate.postForObject(url, stringHttpEntity, Map.class);

        log.info("\n==============浩通门户待办操作 响应: rest={}",JSONObject.toJSONString(result));

        boolean success = MapUtils.getBoolean(result, "success",false);

        return success;
    }

    private String getUrl(String workItemId,String instanceId,String url){
        if (StringUtils.isEmpty(host)){
            List<RelatedCorpSettingModel> list = systemManagementFacade.getAllRelatedCorpSettingModel();
            host = list.stream().filter(l -> l.getSyncType() == OrgSyncType.PULL).findFirst().orElseGet(() -> list.get(0)).getPcServerUrl();
        }

        return StrUtil.format(url,host,workItemId,instanceId);
    }

    private  String getTargetJsonStr(User user){
        JSONObject target = new JSONObject();
        target.put("LoginName",user.getUsername());
        return  target.toJSONString();
    }

//    public static void main(String[] args) {
//        MapBuilder<String, Object> rstBuild = MapBuilder.create(new HashMap<String, Object>())
//                .put("data","1111")
//                .put("url","22222")
//                .put("username","3333")
//                .put("appName","云枢");
//
//
//        log.info("\n==============浩通门户待办 参数: oaSendToDo={}", JSONObject.toJSONString(rstBuild.build()));
//
//        boolean b = post1(sendTodoUrl1, rstBuild.build());
//    }
//
//    private static boolean post1(String url, Object param){
//        log.info("---------OaWorkItemServiceImpl.post--------------param:",JSONObject.toJSONString(param));
//        HttpHeaders headers = new HttpHeaders();
//
//        headers.set("Authorization", tokenService.getAuthorization() );
//
//        HttpEntity stringHttpEntity = new HttpEntity( param, headers);
//        log.info("---------OaWorkItemServiceImpl.post--------------url:",url);
//        log.info("---------OaWorkItemServiceImpl.post--------------stringHttpEntity:",JSONObject.toJSONString(stringHttpEntity));
//        Map result = restTemplate.postForObject(url, stringHttpEntity, Map.class);
//
//        log.info("\n==============浩通门户待办操作 响应: rest={}",JSONObject.toJSONString(result));
//
//        boolean success = MapUtils.getBoolean(result, "success",false);
//
//        return success;
//    }

}
